<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-row>
          <el-col :span="24"
            ><div class="grid-content bg-purple-dark">{{title}}</div></el-col
          >
        </el-row>
        <el-form
          style="margin-top: 20px"
          :model="formData"
          :rules="rules"
          ref="ruleForm"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              v-model="formData.subjectID"
              placeholder="请选择"
              style="width: 35%"
              @change="detailList(formData.subjectID)"
            >
              <el-option
                v-for="item in subjectLists"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select
              v-model="formData.catalogID"
              placeholder="请选择"
              style="width: 35%"
            >
              <el-option
                v-for="item in catalogIDList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select
              v-model="formData.enterpriseID"
              placeholder="请选择"
              style="width: 35%"
              @click.native="QiyeList()"
            >
              <el-option
                v-for="item in shortNameList"
                :key="item.id"
                :label="item.shortName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="province">
            <el-select
              v-model="formData.province"
              placeholder="请选择"
              style="width: 17%"
              :rules="rules.province"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in provinces"
                :key="item"
                @click.native="chooseCity(item)"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="formData.city"
              placeholder="请选择"
              style="width: 17%;;margin-left: 6px;"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in citys"
                :key="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select
              v-model="formData.direction"
              placeholder="请选择"
              style="width: 35%"
            >
              <el-option
                v-for="item in directionList"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="formData.questionType">
              <el-radio
                v-for="item in questionType"
                :key="item.value"
                :label="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="formData.difficulty">
              <el-radio
                v-for="item in difficulty"
                :key="item.value"
                :label="item.value"

              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
          <quillEditor
            v-model="formData.question"
            style="width: 80%"
            ref="QuillEditor"
            :options="editorOption"
            @blur='contentRule'
           >
            </quillEditor>
          </el-form-item>
          <el-form-item label="选项:" v-if="formData.questionType !== 3">
            <div v-for="item in formData.options" :key="item.code" class="baxTi">
              <div
                style="display: flex; display: inline-flex; align-items: center"
              >
                  <el-radio v-if="formData.questionType === 1" v-model="subject" :label="item.code" @change="handelChange(item)">
                    {{ item.code }}:
                  </el-radio>
                  <el-checkbox v-if="formData.questionType === 2" v-model="item.isRight" :false-label="0" :true-label='1' >{{ item.code}}:</el-checkbox>
                <el-input v-model="item.title" style="width: 240px"></el-input>
                <el-upload
                  class="avatar-uploader"
                  :action="item.img"
                  :file-list="file"
                  style="width=100px;height=60px"
                  list-type="picture-card"
                  :on-change='(file,fileList)=>{onChange(item,file,fileList)}'
                >
                 <img  v-if="item.img" :src="item.img" class="avatar">
                  <span>上传图片</span>
                </el-upload>
              </div>
            </div>
             <el-button type="danger"  :disabled="formData.questionType!==2"  @click="handJia">+增加选项与答案</el-button>
          </el-form-item>
          <el-form-item label="解析视频:" style="width:35%">
                <el-input v-model="formData.videoURL"></el-input>
            </el-form-item>
          <el-form-item label="答案解析:" prop="answer">
            <quillEditor
            ref="QuillEditor"
            :options="editorOption"
            @blur='contentRuleAn'
            v-model="formData.answer" style="width: 80%" />
          </el-form-item>
          <el-form-item label="题目备注:" style="width:35%" prop="remarks">
                <el-input v-model="formData.remarks" type="textarea" rows="5"></el-input>
            </el-form-item>
            <el-form-item label="试题标签:"  prop="tags">
                <el-select
                style="width:35%"
                v-model="formData.tags"
                multiple
                filterable
                allow-create
                default-first-option
                >
                <el-option
                v-for="item in simpleList"
                :key="item.value"
                :label="item.label"
                :value="item.label">
                </el-option>
            </el-select>
            </el-form-item>

           <el-form-item>
              <el-button v-if="!this.$route.query.id" type="primary" @click="submitBtn">确认提交</el-button>
              <el-button v-if="this.$route.query.id" type="success" @click="editBtn">确认修改</el-button>
            </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import { simple } from '@/api/hmmm/subjects'
import { simple as Mulu } from '@/api/hmmm/directorys'
import { simple as biaoQian } from '@/api/hmmm/tags'
import { list as Qiye } from '@/api/hmmm/companys'
import { add, detail, update } from '@/api/hmmm/questions.js'
import { citys, provinces } from '@/api/hmmm/citys'
import { questionType, difficulty } from '@/api/hmmm/constants'
import hljs from 'highlight.js'
import 'highlight.js/styles/xcode.css'
export default {
  name: 'QuestionsNew',
  components: { quillEditor },
  data () {
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'],
      [{ list: 'ordered' }, { list: 'bullet' }],
      ['blockquote'],
      ['code-block'],
      ['link', 'image', 'video']
    ]
    return {
      subject: '',
      subjectLists: [],
      provinces: [], // 所有城市
      citys: [], // 当前城市的地区
      shortNameList: [], // 所有企业,
      catalogIDList: [],
      simpleList: [],
      file: [],
      title: '试题录入',
      editorOption: {
        placeholder: '请输入编辑内容',
        theme: 'snow', // 主题风格
        modules: {
          toolbar: {
            container: toolbarOptions // 工具栏
          },
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            },
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector('#quill-upload input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }, // 富文本编辑器配置
      directionList: [
        'o2o',
        '外包服务',
        '企业服务',
        '互联网金融',
        '企业咨询',
        '互联网',
        '电子商务',
        '其他'
      ], // 所有方向
      questionType,
      difficulty,
      formData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '',
        direction: '', // 方向
        question: '', // 题干
        difficulty: 1, // 难度
        questionType: 1, // 题型
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: 1
          },

          {
            code: 'B',
            title: '',
            img: '',
            isRight: 0
          },

          {
            code: 'C',
            title: '',
            img: '',
            isRight: 0
          },

          {
            code: 'D',
            title: '',
            img: '',
            isRight: 0
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: []// 试题标签

      },
      rules: {
        subjectID: [{ required: true, message: '学科不可为空', trigger: ['blur', 'change'] }],
        catalogID: [{ required: true, message: '目录不可为空', trigger: ['blur', 'change'] }],
        enterpriseID: [{ required: true, message: '企业不可为空', trigger: ['blur', 'change'] }],
        province: [{ required: true, message: '城市不可为空', trigger: ['blur', 'change'] }],
        direction: [{ required: true, message: '方向不可为空', trigger: ['blur', 'change'] }],
        questionType: [{ required: true, message: '题型不可为空', trigger: ['blur', 'change'] }],
        difficulty: [{ required: true, message: '难度不可为空', trigger: ['blur', 'change'] }],
        question: [{ required: true, message: '题干不可为空', trigger: ['blur', 'change'] }],
        answer: [{ required: true, message: '解析答案不可为空', trigger: ['blur', 'change'] }]
      }
    }
  },
  created () {
    this.subjectList()
    this.getAllCity()
    // this.detailList()
    // 判断是否有id
    if (this.$route.query.id) {
      this.title = '试题修改'
      // 发送请求
      this.getQuestionDetail()
    }
    this.subject = this.formData.options.find(item => item.isRight === 1)?.code || ''
  },
  methods: {
    // 学科
    async subjectList () {
      const { data } = await simple()
      // console.log(data)
      this.subjectLists = data
    },
    // 目录 标签
    async detailList (val) {
      const { data } = await Mulu({ subjectID: val })
      const { data: data2 } = await biaoQian({ subjectID: val })
      // console.log('标签', res)
      this.simpleList = data2
      this.catalogIDList = data
      this.formData.catalogID = ''
    },
    // 企业
    async QiyeList () {
      const {
        data: { items }
      } = await Qiye({ page: 1, pagesize: 99999 })
      // console.log(items)
      this.shortNameList = items
    },
    // 图片上传
    onChange (item, file, fileList) {
      // console.log(item)
      item.img = URL.createObjectURL(file.raw)
      console.log(item.img)
    },
    // 获取所有城市
    getAllCity () {
      this.provinces = provinces()
      // console.log(this.provinces)
    },
    // 获取区域
    chooseCity (pname) {
      this.citys = citys(pname)
      this.formData.city = ''
      // console.log(this.citys)
    },
    // handelChange (item) {
    //   this.formData.options.forEach(item => {
    //     item.isRight = false
    //   })
    //   item.isRight = true
    // },
    // 添加题目选项
    handJia () {
      this.formData.options.push({
        code: String.fromCharCode(65 + this.formData.options.length), // 生成26个英文字母方法（数组包裹）,
        title: '',
        img: '',
        isRight: false
      })
    },
    // 富文本校验
    contentRule () {
      // console.log(1)
      this.$refs.ruleForm.validateField('question')
    },
    contentRuleAn () {
      this.$refs.ruleForm.validateField('answer')
    },
    // 表单提交
    submitBtn () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return this.$message.error('亲，麻烦填完必填项再来提交')
        // 处理数据
        // console.log(String(this.formData.questionType))
        console.log(this.formData.tags)
        this.formData.questionType = String(this.formData.questionType)
        this.formData.difficulty = String(this.formData.difficulty)
        this.formData.tags = this.formData.tags.join()
        this.formData.options.isRight = this.formData.options.forEach((item) => {
        //   if (item.isRight === true) {
        //     item.isRight = 1
        //   } else {
        //     item.isRight = 0
        //   }
        })
        await add(this.formData)
        // console.log(res)
        this.$message.success('添加成功')
        this.$router.push('/questions/list')
      })
    },
    editBtn () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        // 处理数据
        // console.log(String(this.formData.questionType))
        console.log(this.formData.tags)
        this.formData.questionType = String(this.formData.questionType)
        this.formData.difficulty = String(this.formData.difficulty)
        this.formData.tags = this.formData.tags.join()
        this.formData.options.isRight = this.formData.options.forEach((item) => {
          if (item.isRight === true) {
            item.isRight = 1
          } else {
            item.isRight = 0
          }
        })
        const res = await update({ ...this.formData, id: Number(this.$route.query.id) })
        console.log(res)
        this.$message.success('修改成功')
        window.history.back()
      })
    },
    // 根据id获取具体题目详情
    async getQuestionDetail () {
      const { data } = await detail({ id: this.$route.query.id })
      data.tags = data.tags.split(',')
      this.formData = data
      this.formData.questionType = Number(this.formData.questionType)
      this.formData.difficulty = Number(this.formData.difficulty)
      // this.formData.tags =
    }
  },
  watch: {
    'formData.questionType' () {
      console.log(1111)
    }
  }

}
</script>

<style lang="scss" scoped>
.baxTi {
  margin: 10px 0;
}
.avatar{
  width: 100%;
  height: 100%;
}
::v-deep .el-upload--picture-card {
  margin-left: 10px;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.avatar-uploader{
  overflow: hidden;
}
 ::v-deep .ql-editor{
  widows: 100%;
  height: 200px;
}

</style>
